package com.hyl.design;

import com.hyl.entity.Supplier;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.lang.reflect.Proxy;

/**
 * @Description TODO
 * @Author com.com.hyl
 * @Date 2022/9/13 11:23
 **/
public class IntermediaryJDKProxyFactory {

	public static <T> T create(Object target) throws Exception {
		before();

		Class clz = target.getClass();

		Object obj = sqlSession.getMapper(Supplier.class);

		IntermediaryInvocationhandler handler = new IntermediaryInvocationhandler();
		handler.setTarget(obj);
		return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
				target.getClass().getInterfaces(), handler);
	}

	private static SqlSession sqlSession = null;

	public static void before() throws Exception {
		InputStream is = Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		sqlSession = sessionFactory.openSession();
	}

	public static void after() throws Exception {
		if (sqlSession!=null){
			sqlSession.close();
		}
	}

}
